package com.sakhalin.news.ui.news

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import android.widget.FrameLayout
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.viewinterop.AndroidView
import com.sakhalin.news.network.NewsApi

@Composable
fun NewsDetails(newsHtml: String) {

    val isLightTheme = MaterialTheme.colors.isLight

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(if (isLightTheme) Color.White else Color.Black)
            .verticalScroll(state = rememberScrollState())
    ) {
        if (newsHtml.isNullOrBlank()) {
            CircularProgressIndicator(
                modifier = Modifier
                    .fillMaxSize()
                    .wrapContentSize(align = Alignment.Center)
            )
        } else {
            AndroidView(modifier = Modifier.fillMaxSize(), factory = {
                WebView(it).apply {
                    layoutParams = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )

                    settings.userAgentString = NewsApi.USER_AGENT
                    settings.javaScriptEnabled = true
                    settings.domStorageEnabled = true
                    settings.databaseEnabled = true
                    settings.allowFileAccess = true
                    settings.cacheMode = WebSettings.LOAD_DEFAULT

                    webViewClient = Callback(this)
                    webChromeClient = CustomWebChromeClient(it)

                    clearCache(true)
                    loadDataWithBaseURL(null, newsHtml, "text/html", "UTF-8", null)
                }
            }, update = {
                it.loadDataWithBaseURL(null, newsHtml, "text/html", "UTF-8", null)
            })
        }
    }
}


private class Callback(val webView: WebView) : WebViewClient() {

    @Deprecated("Deprecated in Java")
    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
        view.context.startActivity(intent)
        return true
    }

    override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
        val intent = Intent(Intent.ACTION_VIEW, request.url)
        view.context.startActivity(intent)
        return true
    }

    override fun onPageFinished(view: WebView, url: String) {
        super.onPageFinished(view, url)
        webView.settings.setSupportZoom(true)
        webView.settings.builtInZoomControls = true
        webView.settings.displayZoomControls = false
    }
}

private class CustomWebChromeClient(context: Context) : WebChromeClient() {

    private var customView: View? = null
    private var customViewCallback: CustomViewCallback? = null
    private var originalOrientation = 0
    private var originalSystemUiVisibility = 0
    private val activity: Activity = context as Activity

    override fun onHideCustomView() {

        (activity.window.decorView as FrameLayout).removeView(customView)
        activity.window.decorView.setSystemUiVisibility(originalSystemUiVisibility)
        activity.requestedOrientation = originalOrientation

        customViewCallback?.onCustomViewHidden()
        customView = null
        customViewCallback = null
    }

    override fun onShowCustomView(paramView: View, paramCustomViewCallback: CustomViewCallback) {
        if (customView != null) {
            onHideCustomView()
            return
        }

        customView = paramView
        originalSystemUiVisibility = activity.window.decorView.getSystemUiVisibility()
        originalOrientation = activity.requestedOrientation
        customViewCallback = paramCustomViewCallback

        (activity.window.decorView as FrameLayout).addView(customView, FrameLayout.LayoutParams(-1, -1))
        activity.window.decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_IMMERSIVE or
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        )
    }
}
